import { PointerEvent } from 'leafer-ui'
export class MouseEvent {
    name = 'MouseEvent'
    constructor(instance) {
        this.instance = instance;
        this.size = { width: 0, height: 0 };
        this.start = null;
        this.downListener = null;
        this.upListener = null;
    }

    MouseEvent() {
        return {
            handles: (callback) => {
                const self = this;
                // 如果已经创建了渲染并且没有事件监听器，则初始化它们
                if (this.instance.create && !this.downListener && !this.upListener) {
                    this.downListener = (e) => {
                        self.start = e.getPage();
                    };

                    this.upListener = (e) => {
                        const point = e.getPage()

                        let x = point.x - self.start.x;
                        let y = point.y - self.start.y;

                        // 计算尺寸
                        self.size.width = Math.abs(x);
                        self.size.height = Math.abs(y);
                        // 执行回调并传递尺寸信息
                        callback(self.size, self.start);

                        // 清理事件监听器，并设置render.create为false
                        self.cleanupListeners();
                        self.instance.create = false;
                    };

                    // 添加事件监听器
                    this.instance.app.on(PointerEvent.DOWN, this.downListener);
                    this.instance.app.on(PointerEvent.UP, this.upListener);
                }
            }
        };
    }
    // 可能需要一个方法来清理监听器
    cleanupListeners() {
        if (this.downListener && this.upListener) {
            this.instance.app.off(PointerEvent.DOWN, this.downListener);
            this.instance.app.off(PointerEvent.UP, this.upListener);
            this.downListener = null;
            this.upListener = null;
        }
    }
}